/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.t4.irc.net;

import com.t4.irc.IRC;
import com.t4.irc.Logger;
import com.t4.irc.net.packet.PacketFactory;
import com.t4.irc.net.packet.PacketManager;

import java.io.*;

/**
 * Connector class
 * @author T4_
 */
public class Connector implements Runnable {

    /** Logger */
    private Logger log = new Logger(this.getClass());

    /** The IRC socket */
    private IRCSocketFactory ircSocket;

    /** Reads from the socket */
    private BufferedReader reader;

    /** Writes to the socket */
    private BufferedWriter writer;
    
    /** The connect time */
    private long connectTime;
    
    /** Joined a channel? */
    private boolean joined = false;

    public Connector() {
        try {
            this.ircSocket = new IRCSocketFactory();
            this.reader = new BufferedReader(new InputStreamReader(this.ircSocket.getInputStream()));
            this.writer = new BufferedWriter(new OutputStreamWriter(this.ircSocket.getOutputStream()));
        } catch (Exception e) {
            log.error("Error creating IRCSocket: " + e);
            e.printStackTrace();
        }
    }

    /**
     * Sends a raw line to the server
     * @param line
     */
    public void sendRawLine(String line) {
        try {
            writer.write(line + "\r\n");
            writer.flush();
            log.debug("WROTE: " + line);
        } catch (IOException e) {
            log.error("Error writing " + line + ", " + e);
        }
    }

    /**
     * Closes the current IRC Socket
     */
    public void close() {
        try {
            ircSocket.getSocket().close();
        } catch (IOException e) {
            log.error("Error closing irc socket: " + e);
        }
    }

    /**
     * Runnable method to handle raw I/O
     */
    public void run() {
        try {
            sendRawLine("NICK " + IRC.getConfiguration().getNickname());
            sendRawLine("USER " + IRC.getConfiguration().getIdent() + " 8 * :" + IRC.VERSION);

            log.debug("Connecting...");
            IRC.getGui().pushText("> Connecting...");
            
            connectTime = System.currentTimeMillis();
            
            String readLine;
            while((readLine = reader.readLine()) != null) {
                log.debug("READ: " + readLine);

                String response = PacketManager.getResponse(readLine);
                if(response != null)
                    sendRawLine(response + "\r\n");
                
                if(!joined) {
                	IRC.getGui().pushText("> Connected!");
                	PacketFactory.join(IRC.getConfiguration().getChannel());
                	joined = true;
                }
            }
        } catch (IOException e) {
            log.error("Error whilst processing I/O " + e);
        }
    }
}
